{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Python高级用法总结"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "list =  [1, 5, 7, 8, 9, 10]\n"
     ]
    }
   ],
   "source": [
    "'''\n",
    "\n",
    "列表推导（list comprehensions）\n",
    "\n",
    "'''\n",
    "\n",
    "'''\n",
    "\n",
    "一、列表解析式\n",
    "\n",
    "    官方解释：列表解析式是Python内置的非常简单却强大的可以用来创建list的生成式。\n",
    "    \n",
    "              强大具体如何体现？\n",
    "              \n",
    "              使用列表解析式的写法更加简短，除此之外，因为是Python内置的用法，底层使用C语言实现，相较于编写Python代码而言，运行速度更快。\n",
    "\n",
    "'''\n",
    "\n",
    "numbs = [1,2,3,5,7,736,87,6,78,18,16]\n",
    "list = [item for item in range(len(numbs)) if numbs[item] % 2 == 0]\n",
    "print('list = ',list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1, 2, 3], [1, 4, 5]]\n"
     ]
    }
   ],
   "source": [
    "# 将一个三维列表中所有一维数据为1的元素合并，组成新的二维列表。\n",
    "\n",
    "result_list=[[1,2,3],[1,4,5],[4,7,6]]\n",
    "\n",
    "listnew = [item for item in result_list if item[0] == 1]\n",
    "print(listnew)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "结果  0 : I\n",
      "结果  1 : love\n",
      "结果  2 : python\n"
     ]
    }
   ],
   "source": [
    "'''\n",
    "\n",
    " 对于一个列表，既要遍历索引又要遍历元素。\n",
    " \n",
    " 使用Python内建函数enumerate，在循环中更好的获取获得索引。\n",
    "\n",
    "\n",
    "'''\n",
    "\n",
    "\n",
    "array = ['I','love','python']\n",
    "\n",
    "for i, element in enumerate(array):\n",
    "    resut = list[i] = '%d : %s' %(i,element)\n",
    "    print('结果 ',resut)  \n",
    "    # print(i,array[i])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "星期0：Monday\n",
      "星期1：Tuesday\n",
      "星期2：Wednesday\n",
      "星期3：Thursday\n",
      "星期4：Friday\n",
      "星期5：Staturday\n",
      "星期6：Sunday\n"
     ]
    }
   ],
   "source": [
    "dayList = ['Monday','Tuesday','Wednesday','Thursday','Friday','Staturday','Sunday']\n",
    "\n",
    "for i, day in enumerate(dayList):\n",
    "    print('星期{}：{}'.format(i,day))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"\\n\\n迭代器和生成器\\n\\n\\n\\n\\n\\n\\n\\n\\n迭代器（Iterator）\\n\\n这里的迭代可以指for循环，在Python中，对于像list，dict和文件等而言，都可以使用for循环，但是它们并不是迭代器，它们属于可迭代对象。\\n什么可迭代对象\\n最简单的解释：可以使用for...in...语句进行循环的对象，就是可迭代对象（Iterable），可以使用isinstance()方法进行判断。\\n\\nfrom collections import Iterable \\ntype = isinstance('python', Iterable)\\nprint type\\n\\n\""
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'''\n",
    "\n",
    "迭代器和生成器\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "迭代器（Iterator）\n",
    "\n",
    "这里的迭代可以指for循环，在Python中，对于像list，dict和文件等而言，都可以使用for循环，但是它们并不是迭代器，它们属于可迭代对象。\n",
    "什么可迭代对象\n",
    "最简单的解释：可以使用for...in...语句进行循环的对象，就是可迭代对象（Iterable），可以使用isinstance()方法进行判断。\n",
    "\n",
    "from collections import Iterable \n",
    "type = isinstance('python', Iterable)\n",
    "print type\n",
    "\n",
    "'''\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'list_iterator'>\n",
      "9\n",
      "4\n"
     ]
    }
   ],
   "source": [
    "'''\n",
    "\n",
    "什么是迭代器\n",
    "迭代器指的是可以使用next()方法来回调的对象，可以对可迭代对象使用iter()方法，将其转换为迭代器。\n",
    "'''\n",
    "\n",
    "\n",
    "temp = iter([9,4,7,2,1])\n",
    "print(type(temp))\n",
    "print(next(temp))\n",
    "print(next(temp))\n",
    "\n",
    "\n",
    "'''\n",
    "\n",
    "\n",
    "此时temp就是一个迭代器。所以说，迭代器基于两个方法：\n",
    "\n",
    "next：返回下一个项目\n",
    "iter 返回迭代器本身\n",
    "可理解为可被next()函数调用并不断返回下一个值的对象就是迭代器，在定义一个装饰器时将需要同时定义这两个方法。\n",
    "\n",
    "迭代器的优势\n",
    "\n",
    "在构建迭代器时，不是将所有的元素一次性的加载，而是等调用next方法时返回元素，所以不需要考虑内存的问题。\n",
    "迭代器应用场景\n",
    "\n",
    "那么，具体在什么场景下可以使用迭代器呢？\n",
    "\n",
    "数列的数据规模巨大\n",
    "数列有规律，但是不能使用列表推导式描述。\n",
    "\n",
    "\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'generator'>\n",
      "g =  <generator object <genexpr> at 0x00000217372206D8>\n"
     ]
    }
   ],
   "source": [
    "'''\n",
    "\n",
    "生成器\n",
    "生成器是一种高级迭代器，使得需要返回一系列元素的函数所需的代码更加的简单和高效（不像创建迭代器代码那般冗长）。\n",
    "\n",
    "生成器函数\n",
    "生成器函数基于yield指令，可以暂停一个函数并返回中间结果。当需要一个将返回一个序列或在循环中执行的函数时，就可以使用生成器，因为当这些元素被传递到另一个函数中进行后续处理时，一次返回一个元素可以有效的提升整体性能。\n",
    "常见的应用场景是使用生成器的流数据缓冲区。\n",
    "\n",
    "生成器表达式\n",
    "生成式表达式是一种实现生成器的便捷方式，将列表推导式的中括号替换为圆括号。\n",
    "和列表推导式的区别：列表生成式可以直接创建一个表，但是生成器表达式是一种边循环边计算，使得列表的元素可以在循环过程中一个个的推算出来，不需要创建完整的列表，从而节省了大量的空间。\n",
    "\n",
    "\n",
    "'''\n",
    "\n",
    "\n",
    "g = (x *x for x in range(10))\n",
    "print(type(g))\n",
    "print('g = ', g)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<map at 0x2173674abe0>"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'''\n",
    "\n",
    "lambda表达式（匿名函数）\n",
    "lambda表达式纯粹是为了编写简单函数而设计，起到了一个函数速写的作用，使得简单函数可以更加简洁的表示。\n",
    "lambda和def的区别\n",
    "lambda表达式可以省去定义函数的过程，让代码更加的简洁，适用于简单函数，编写处理更大业务的函数需要使用def定义。\n",
    "lambda表达式常搭配map(), reduce(), filter()函数使用\n",
    "\n",
    "map(): map函数接受两个参数，一个是函数，一个是序列，其中，函数可以接收一个或者多个参数。map将传入的函数依次作用于序列中的每个元素，将结果作为新的列表返回。\n",
    "\n",
    "\n",
    "'''\n",
    "\n",
    "\n",
    "map(str,[1,2,5,3,7,6,4])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "myfunc is: myfunc\n",
      "myfunc is:  wrapper\n",
      "start func\n",
      "end func\n",
      "The function timing is 800.929785 ms\n"
     ]
    }
   ],
   "source": [
    "\n",
    "'''\n",
    "\n",
    "\n",
    "装饰器\n",
    "装饰器本质是一个Python函数，它可以让其它函数在没有任何代码变动的情况下增加额外功能。有了装饰器，我们可以抽离出大量和函数功能本身无关的雷同代码并继续重用。经常用于具有切面需求的场景：包括插入日志、性能测试、事务处理、缓存和权限校验等。\n",
    "\n",
    "\n",
    "'''\n",
    "\n",
    "\n",
    "import time \n",
    "\n",
    "def get_time(func):\n",
    "    def wrapper():\n",
    "        startTime = time.time()\n",
    "        func()\n",
    "        endTime = time.time()\n",
    "        processTime = (endTime - startTime) * 1000\n",
    "        print(\"The function timing is %f ms\" % processTime)\n",
    "    return wrapper\n",
    "\n",
    "\n",
    "def myfunc():\n",
    "    print(\"start func\")\n",
    "    time.sleep(0.8)\n",
    "    print( \"end func\")\n",
    "    \n",
    "print(\"myfunc is:\", myfunc.__name__)\n",
    "myfunc = get_time(myfunc)\n",
    "print( \"myfunc is: \", myfunc.__name__)\n",
    "myfunc()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "myfunc is:  wrapper\n",
      "start func\n",
      "end func\n",
      "The function timing is 801.775694 ms\n"
     ]
    }
   ],
   "source": [
    "@ get_time\n",
    "def myfunc():\n",
    "    print(\"start func\")\n",
    "    time.sleep(0.8)\n",
    "    print(\"end func\")\n",
    "\n",
    "print(\"myfunc is: \", myfunc.__name__)\n",
    "myfunc()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### zip()函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dragon 男 80\n",
      "意涵 女 90\n",
      "Solider 男 95\n",
      "中国龙 男 95\n"
     ]
    }
   ],
   "source": [
    "'''\n",
    "\n",
    "该函数用于将多个可迭代对象作为参数，依次将对象中对应的元素打包成一个个元组，然后返回由这些元组组成的对象。\n",
    "\n",
    "'''\n",
    "\n",
    "\n",
    "\n",
    "names = ['Dragon','意涵','Solider','中国龙']\n",
    "sexes = ['男','女','男','男']\n",
    "scores = [80,90,95,95]\n",
    "\n",
    "\n",
    "for name, sex, score in zip(names,sexes,scores):\n",
    "    print('{} {} {}'.format(name,sex,score))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dragon 男 80\n",
      "意涵 女 90\n",
      "Solider 男 95\n"
     ]
    }
   ],
   "source": [
    "\n",
    "'''\n",
    "\n",
    "注意：如果各个可迭代对象的元素个数不一致，则返回的对象长度与最短的可迭代对象相同。例如，对上面的例子，列表scores减少一个元素，修改如下：\n",
    "\n",
    "'''\n",
    "\n",
    "\n",
    "names = ['Dragon','意涵','Solider','中国龙']\n",
    "sexes = ['男','女','男','男']\n",
    "scores = [80,90,95]\n",
    "\n",
    "for name, sex, score in zip(names,sexes,scores):\n",
    "    print('{} {} {}'.format(name,sex,score))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a == b :  True\n",
      "a is b :  True\n"
     ]
    }
   ],
   "source": [
    "# 关键字is 和 == 的区别\n",
    "\n",
    "a = 'test'\n",
    "\n",
    "b = 'test'\n",
    "\n",
    "print('a == b : ',a == b)\n",
    "print('a is b : ', a is b)\n",
    "\n",
    "#  is 判断是否是一个ID， == 判断内容是否一致。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Counter({'S': 31, 'Y': 28, 'G': 26, 'C': 26, 'A': 24, 'O': 21, 'D': 20, 'V': 20, 'H': 20, 'T': 20, 'X': 20, 'B': 19, 'W': 19, 'I': 19, 'U': 19, 'F': 18, 'P': 18, 'M': 17, 'E': 16, 'L': 16, 'Z': 15, 'R': 15, 'Q': 14, 'K': 14, 'J': 13, 'N': 12})\n"
     ]
    }
   ],
   "source": [
    "'''\n",
    "\n",
    "Counter\n",
    "用来统计元素出现的次数\n",
    "\n",
    "\n",
    "'''\n",
    "\n",
    "from collections import Counter\n",
    "def radom_char():\n",
    "    import random\n",
    "    ret = ''\n",
    "    for i in range(500):\n",
    "        ret +=chr(random.randint(65,90))\n",
    "    return ret\n",
    "\n",
    "word_seq = Counter(radom_char())\n",
    "print(word_seq)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
